<?php
class EditCategoryForm extends Form{
	private $cat=false, $filter_group=false, $zones = array();
	
	function EditCategoryForm()
	{
		Form::Form('EditCategoryForm');
		CGlobal::$website_title='Sửa Danh mục';
		
		$this->link_css('style/manage_item.css');
		
		if(Url::get('cmd')=='edit')
		{
			$id=(int)Url::get('id',0);
			
			if($id)$this->cat=DB::select('category','id='.$id);
			
			if(!$this->cat){
				Url::redirect_current();
			}
			
			if($this->cat['parent_id'] == 0){
				$re = DB::query("SELECT z.id, z.name FROM (SELECT zoneid, catid FROM category_zone_cat WHERE catid=$id) AS c LEFT JOIN category_zone AS z ON z.id=c.zoneid");
				if($re){
					while($zone = mysql_fetch_assoc($re)){
						$this->zones[$zone['id']] = $zone;	
					}
				}
			}
			
			
			#############################################################################
			#Remove filter_group khỏi danh mục
			$fgroup_remove = (int)Url::get('fgroup_remove',0);
			
			if($fgroup_remove)
			{
				Category::remove_cat_group_filer($this->cat['id'],$fgroup_remove);
				
				Url::redirect_current(array('cmd','id'));
			}
			
			#Remove filter_group khỏi danh mục
			#############################################################################
			
			#############################################################################
			#Thêm filter_group vào danh mục
			$fgroup_add = (int)Url::get('fgroup_add',0);
			
			if($fgroup_add)
			{
				$this->filter_group	= DB::select('filter_group','id='.$fgroup_add);
				
				if($this->filter_group)
				{
					if($this->filter_group['catids'])
					{
						$arr 	= explode(',', $this->filter_group['catids'] . "," . $this->cat['id']);
						
						$arr 	= array_change_key_case(array_unique($arr));
						
						$catids = implode(',', array_change_key_case($arr));
					}
					else
					{
						$catids = $this->cat['id'];
					}
					
					DB::update("filter_group",array("catids"=>$catids),"id=$fgroup_add");
				}
				
				AZLib::getFilters(1);
				
				Url::redirect_current(array('cmd','id'));
			}
			
			#Thêm filter_group vào danh mục
			#############################################################################
		}
		else{
			$this->cat=array(	
							'name'			=>'',
							'brief_name'	=>'',
							'keywords'		=>'',
							'description'	=>'',
							'position'		=>1,
							'parent_id'		=>0,
							'ref_id'		=>0,
							'status'		=>'HOME',
							'tag_search'	=>'',
							'img_server'	=>0,
							'price_str'		=>'',
							'recomend'		=>'',
							); 
		}
		
		AZLib::getFilters();
	}
	
	function on_submit()
	{
		$gfsubmit = Url::get("gfsubmit");
		
		if($gfsubmit)//Cập nhật thuộc tính
		{
			$fgroup_id = (int)implode(array_keys($gfsubmit));
			if($fgroup_id)
			{
				$fgroup = DB::select("filter_group","id=$fgroup_id");
				
				if($fgroup)
				{
					$gf_name 	= Url::get('gf_name');
					$gf_pos 	= Url::get('gf_pos');
					
					if(isset($gf_name[$fgroup_id],$gf_pos[$fgroup_id]) && $gf_name[$fgroup_id] && $gf_pos[$fgroup_id])
					{
						$gf_name 	= $gf_name[$fgroup_id];
						$gf_pos 	= $gf_pos[$fgroup_id];
					
						if($fgroup['name'] != $gf_name || $fgroup['pos'] != $gf_pos)//Đổi tên, vị trí
						{
							$max_pos	=	(int)DB::fetch("SELECT max(pos) AS max_pos FROM filter_group",'max_pos',0);
				
							if($gf_pos > $max_pos)
							{
								$gf_pos = $max_pos;
							}
							elseif($gf_pos<=0)
							{
								$gf_pos = $fgroup['pos'];
							}
						
							DB::update('filter_group', array("name" => $gf_name, "pos" => $gf_pos) , "id=$fgroup_id");
					
							if(DB::select('filter_group',"pos=$gf_pos AND id!=$fgroup_id"))
							{
								DB::query("UPDATE filter_group SET pos=pos+1 WHERE pos>=$gf_pos AND pos<={$fgroup['pos']} AND id!=$fgroup_id");
							}
							
							AZLib::getFilters(1);
						}
					}
				}
			}
			
			Url::redirect_current(array('cmd','id'));
		}
		
		$submit = Url::get("submit");
		
		if($submit == "Thêm nhóm thuộc tính")
		{
			$gfilter_name	= Url::get('gfilter_name');
			$gfilter_pos	= Url::get('gfilter_pos');
			
			if($gfilter_name!='' && $gfilter_pos)
			{
				$gfilter_group =	array(	
											'name'		=>$gfilter_name,
											'catids'	=>$this->cat['id'],
											'pos'		=>$gfilter_pos
										 ); 

				$max_pos	=	(int)DB::fetch("SELECT max(pos) AS max_pos FROM filter_group",'max_pos',0);
			
				if($gfilter_pos	>	$max_pos || $gfilter_pos<=0)
				{
					$gfilter_pos	=	$max_pos+1;
				}
				
				$gfilter_group['pos'] = $gfilter_pos;
				
				$id = DB::insert('filter_group', $gfilter_group);
				
				if($id && DB::select('filter_group','pos="'.$gfilter_pos.'" AND id!='.$id)){
					DB::query('UPDATE filter_group SET pos=pos+1 WHERE pos>='.$gfilter_pos.' AND id!='.$id);
				}
			}
			
			AZLib::getFilters(1);
			
			Url::redirect_current(array('cmd','id'));
		}
		
		$name		=Url::get('name');
		$brief_name	=Url::get('brief_name');
		$keywords	=Url::get('keywords');
		$description=Url::get('description');
		$parent_id	=Url::get('parent_id');
		$zoneids	=Url::get('zoneids');
		
		$ref_id		=Url::get('ref_id');
		$status		=Url::get('status','HIDE');
		$position	=Url::get('position');
		$tag_search	=Url::get('tag_search');
		
		$price_str	=trim(Url::get('price_str'));
		$recomend	=trim(Url::get('recomend'));
		
		if($price_str)
		{
			function check_price_str($price)
			{
				return Url::cdouble(trim($price));
			}
			
			$price_ar = array_unique(array_map('check_price_str',explode(",",$price_str)));
			
			$price_str = '';
			
			if($price_ar)
			{
				asort($price_ar);
				
				foreach ($price_ar as $price)
				{
					if($price > 0)
					{
						$price_str .= ($price_str != '' ? ',' : '') . $price;
					}
				}
			}
		}
		
		$this->checkFormInput('Tên Danh mục','name',$name,'str',true,'',1,255);
		$this->checkFormInput('Tên vắn tắt','brief_name',$brief_name,'str',false,'',1,255);
		//$this->checkFormInput('Từ khoá','keywords',$keywords,'str',false,'',0,20);
		$this->checkFormInput('Mô tả','description',$description,'str',false,'',0,250);
		
		if(Url::get('cmd')=='edit' && $this->cat['parent_id']==0 && $parent_id && DB::select("category",'parent_id='.$this->cat['id'])){
			$this->setFormError("parent_id",'Không thể chuyển "Danh mục có danh mục con" thành một "Danh mục con" của "Danh mục khác" được!');
		}
		
		if(!$this->errNum){
			$new_row =array(	
							'name'			=>$name,
							'brief_name'	=>$brief_name?$brief_name:$name,
							'keywords'		=>AZLib::word_limit($keywords,20,''),
							'description'	=>$description,
							'parent_id'		=>$parent_id,
							'ref_id'		=>$ref_id,
							'status'		=>$status,
							'tag_search'	=>$tag_search,
							'img_server'	=>IMAGE_SERVER_NO,
							'price_str'		=>$price_str,
							'recomend'		=>$recomend
							); 
								
			if(Url::get('cmd')=='edit'){
				if($position>0 && $position!=$this->cat['position']){
					$max_pos=(int)DB::fetch("SELECT max(position) AS max_pos FROM category WHERE parent_id=".$parent_id,'max_pos');
					if($position>$max_pos){
						$position=$max_pos+1;
					}
					$new_row['position']=$position;
				}
				else{
					$position=$this->cat['position'];
				}
				
				$id=$this->cat['id'];
				DB::update('category', $new_row,'id='.$this->cat['id']);
				
				/*if($this->cat['parent_id']==0 && $parent_id){
					DB::update('category', array('parent_id'=>0),'parent_id='.$this->cat['parent_id']);
				}*/
			}
			else{
				$max_pos=(int)DB::fetch("SELECT max(position) AS max_pos FROM category WHERE parent_id=".$parent_id,'max_pos');
				
				if($position>$max_pos || $position==0) 
				$position=$max_pos+1;
				
				$new_row['position']=$position;
				
				$id = DB::insert('category', $new_row);
			}
			
			if($_FILES['cat_image']['tmp_name']){
				
				if(Url::get('cmd')=='edit')//sửa -> up ảnh -> xóa ảnh cũ
				{
					AZLib::ftp_image_delete_file('category/'.$this->cat['id'].'.gif',$this->cat['img_server']);
				}
				
				/*if(AZLib::ftp_image_connect(IMAGE_SERVER_NO)){
					if(!AZLib::ftp_check_dir('category/',true,IMAGE_SERVER_NO)){
						break ;
					}
						
					$file_name	='category/'.$id.'.gif';
					$sourceName =$_FILES['cat_image']['tmp_name'];
					AZLib::ftp_image_put_file($file_name,$sourceName,IMAGE_SERVER_NO);
					//@fopen('http://'.IMAGE_PATH.'?del_cat=1',"r");
				}*/
				
				if(AZLib::ftp_check_dir('category/',true,IMAGE_SERVER_NO))
				{
					$file_name	='category/'.$id.'.gif';
					$sourceName =$_FILES['cat_image']['tmp_name'];
					AZLib::ftp_image_put_file($file_name,$sourceName,IMAGE_SERVER_NO);
					//@fopen('http://'.IMAGE_PATH.'?del_cat=1',"r");
				}
			}
			
			if($id && DB::select('category','position="'.$position.'" AND id!="'.$id.'" AND parent_id="'.$parent_id.'"')){
				DB::query('UPDATE category SET position=position+1 WHERE position>='.$position.' AND position<='.$this->cat['position'].' AND parent_id="'.$parent_id.'" AND id!='.$id);
			}
			
			$all_zones  = $this->zones;
			$sql_inset = "";
			if($zoneids){
				foreach ($zoneids as $zoneid){
					if(isset($all_zones[$zoneid])){
						unset($all_zones[$zoneid]);
					}
					else{
						$sql_inset.=($sql_inset!=''?',':'')."($zoneid,$id)";
					}
				}
			}
			
			if($sql_inset){
				$sql_inset="INSERT INTO category_zone_cat (zoneid, catid) VALUES ".$sql_inset;
				DB::query($sql_inset);
			}
			
			if($all_zones){
				$zoneids = implode(",",array_keys($all_zones));
				
				if($zoneids){
					DB::query("DELETE FROM category_zone_cat WHERE catid=$id AND zoneid IN($zoneids)");
				}
			}
			
			//AZLib::del_cache_zone_cat();
			AZLib::getCats(1,true);
			
			if(Url::get('cmd')=='edit' && $this->cat['parent_id'] != $parent_id){//đổi danh mục cha => cập nhật lại tin
				$catid 	 = $this->cat['id'];
				$level_1 = 0;
				$level_2 = 0;
				
				if($parent_id){
					if(CGlobal::$allCategories[$parent_id]['parent_id']){
						$level_1 = CGlobal::$allCategories[$parent_id]['parent_id'];
						$level_2 = $parent_id;
					}
					else{
						$level_1 = $parent_id;
						$level_2 = $catid;
					}
				}
				else{
					$level_1 = $catid;
					$level_2 = 0;
				}
				
				DB::update("item",array("level_1_catid"=>$level_1,"level_2_catid"=>$level_2),"category_id=$catid");
				
				if(MEMCACHE_ON){	
					AZMemcache::clear();
				}
			}
			
			if($this->cat){
				Url::redirect_current();
			}
			else{
				Url::redirect_current(array('cmd'));	
			}
		}
	}
	
	function draw()
	{	
		global $display;
		$this->beginForm(true);
		
		$cmd=Url::get('cmd');
		$display->add('cmd',$cmd);
		
		$re=DB::query("SELECT id,name,parent_id ,position FROM category ORDER BY parent_id,position");
		
		$all_cats=array();
		$all_subcats=array();
		$all_top_cat=array(0=>'-Chọn danh mục cha-');
		
		$level1_cats = array();
		$level2_cats = array();
		
		if($re){
			while($cat = mysql_fetch_assoc($re))
			{
				$cat['name'] = "[{$cat['id']}] {$cat['name']}";
				
				if($cat['parent_id'])//Là danh mục cấp 2
				{
					if(!isset($all_cats[$cat['parent_id']]))
					{
						$level1_cats[$cat['parent_id']] = array('id'=>$cat['parent_id'],'name'=>"[{$cat['parent_id']}] Đã xóa (ko tồn tại)","max"=>$cat['position']);
					}
					
					$all_subcats[$cat['parent_id']][$cat['id']] = $cat;
						
					$cat['max'] 	= 0;
					
					if($cat['position'] > $level1_cats[$cat['parent_id']]['max'])
					{
						 $level1_cats[$cat['parent_id']]['max'] = $cat['position'];
					}
					
					$level2_cats[$cat['id']] = $cat;
				}
				else
				{
					$cat['max'] 				= 0;
					
					$level1_cats[$cat['id']] 	= $cat;
					
					if(!isset($all_subcats[$cat['id']]))
					{
						$all_subcats[$cat['id']] = array();
					}
				}
				
				$all_cats[$cat['id']]=$cat;
			}
		}
		
		$display->add('level1_cats',json_encode($level1_cats));
		$display->add('level2_cats',json_encode($level2_cats));
		
		foreach($all_subcats as $topid=>$subcats)
		{
			if(isset($level1_cats[$topid]) && $level1_cats[$topid]['max'])
			{
				if(!isset($all_cats[$topid]))
				{
					$all_cats[$topid] = array('id'=>$topid,'name'=>"[$topid] Đã xóa (ko tồn tại)");
				}
				
				$all_cats[$topid]['name'].=" ({$level1_cats[$topid]['max']})";
			}
			
			$all_top_cat[$topid]=$all_cats[$topid]['name'];
			
			foreach ($subcats as $subcat)
			{
				if(isset($level2_cats[$subcat['id']]) && $level2_cats[$subcat['id']]['max']){
					$subcat['name'].=" ({$level2_cats[$subcat['id']]['max']})";
				}
				
				$all_top_cat[$subcat['id']] = "-----".$subcat['name'];
			}
		}
		
		if(!isset($this->cat['id']))
		$this->cat['id']=0;
		$display->add('cat_image',AZLib::getImageThumb('category/'.$this->cat['id'].'.gif',200,200,0,$this->cat['img_server']));
		$display->add('msg',$this->showFormErrorMessages(true));
		$display->add('name',Url::get('name',$this->cat['name']));
		$display->add('brief_name',Url::get('brief_name',$this->cat['brief_name']));
		$display->add('keywords',Url::get('keywords',$this->cat['keywords']));
		$display->add('description',Url::get('description',$this->cat['description']));
		$display->add('option_parent_id',AZLib::getOption($all_top_cat,Url::get('parent_id',$this->cat['parent_id'])));
		$display->add('option_status',AZLib::getOption(array('HIDE'=>'Ẩn','SHOW'=>'SHOW','HOME'=>'HOME'),Url::get('status',$this->cat['status'])));
		
		
		$max_pos = 1 + DB::fetch("SELECT MAX(position) AS max_pos FROM category WHERE parent_id=0","max_pos",0);
		
		$display->add('max_pos',$max_pos);
		
		
		if(Url::get('cmd')=='add' || (Url::get('cmd')=='edit' && $this->cat['parent_id'] == 0)){//Sửa danh mục
			$zones = array();
			if(Url::get('cmd')=='edit' && $this->cat['parent_id'] == 0){//Sửa danh mục
				$zones = $this->zones;
			}
			
			$re=DB::query("SELECT id,name, status FROM category_zone ORDER BY position");
	
			$all_zone=array();
			if($re){
				while($zone = mysql_fetch_assoc($re))
				{
					if($zone['status'] == 0){
						$zone['name'].=' (Ẩn)';
					}
					
					$all_zone[$zone['id']] = $zone['name'];
				}
			}
			
			$display->add('option_zones',AZLib::getOptionMulti($all_zone,array_keys($zones)));
		}
		
		if(Url::get('cmd')=='edit'){//Sửa danh mục
			$display->add('option_position',AZLib::getOptionNum(1,$max_pos,Url::get('position',$this->cat['position'])));
		
			$display->add('cur_position',$this->cat['position']);
		}
		else{
			$display->add('option_position',AZLib::getOptionNum(1,$max_pos,Url::get('position',$max_pos)));
			$display->add('cur_position',0);
		}
		
		
		$filter_groups 			= array();
		$other_filter_groups 	= CGlobal::$all_gfilters;
		
		$max_pos_gfilter = 1;

		if($this->cat['id'])
		{
			/*$max_pos_gfilter = 1 + DB::fetch("SELECT MAX(pos) AS max_pos FROM filter_group WHERE catid=".$this->cat['id']."","max_pos",0);
		
			$re = DB::query("SELECT * FROM filter_group WHERE catid=".$this->cat['id']." ORDER BY pos");
			
			if($re)
			{
				while($filter_group = mysql_fetch_assoc($re))
				{
					$filter_group['link'] 	= Url::build_current(array('cmd'=>'filter','fgroup_id'=>$filter_group['id']));
					
					$filter_group['del'] 	= Url::build_current(array('cmd','id','fgroup_del'=>$filter_group['id']));
					
					$filter_groups[$filter_group['id']] = $filter_group;
				}
			}*/
			
			if(isset(CGlobal::$filters[$this->cat['id']]))
			{
				foreach (CGlobal::$filters[$this->cat['id']] as $filter_group)
				{
					unset($other_filter_groups[$filter_group['id']]);
					
					if($max_pos_gfilter <= $filter_group['pos'])
					{
						$max_pos_gfilter = $filter_group['pos'] + 1;
					}
					
					$filter_group['link'] 	= Url::build_current(array('cmd'=>'filter','fgroup_id'=>$filter_group['id']));
					
					$filter_group['remove'] 	= Url::build_current(array('cmd','id','fgroup_remove'=>$filter_group['id']));
					
					$filter_groups[$filter_group['id']] = $filter_group;
				}
			}
		}
		
		if($other_filter_groups)
		{
			foreach ($other_filter_groups as $filter_group)
			{
				if($max_pos_gfilter <= $filter_group['pos'])
				{
					$max_pos_gfilter = $filter_group['pos'] + 1;
				}
				
				$filter_group['link'] 	= Url::build_current(array('cmd'=>'filter','fgroup_id'=>$filter_group['id']));
				
				$filter_group['add'] 	= Url::build_current(array('cmd','id','fgroup_add'=>$filter_group['id']));
				
				$other_filter_groups[$filter_group['id']] = $filter_group;
			}
		}
		
		$display->add('filter_groups',$filter_groups);
		$display->add('other_filter_groups',$other_filter_groups);
		
		$display->add('catid',$this->cat['id']);
		$display->add('parent_id',$this->cat['parent_id']);

		$display->add('option_gfilter_pos',AZLib::getOptionNum(1,$max_pos_gfilter,$max_pos_gfilter));
		
		$display->add('tag_search',Url::get('tag_search',$this->cat['tag_search']));
		
		$display->add('price_str',Url::get('price_str',$this->cat['price_str']));
		$display->add('recomend',Url::get('recomend',$this->cat['recomend']));
		
		$display->output('edit');
		$this->endForm();
	}
}
?>